package com.mifan.security;/*
 * @Author Milan
 * @Date 2024/9/13 18:20
 */

import com.alibaba.fastjson.JSON;
import com.mifan.common.Results;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    // TODO 认证失败会走入到这个方法
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        System.out.println("异常信息：" + authException.getMessage());
        System.out.println("异常类型：" + authException.getClass().getName());
        String message = authException.getMessage();
        if (authException instanceof InsufficientAuthenticationException) {
            message = "未认证";
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        Results<Object> failure = Results.failure(message);
        String string = JSON.toJSONString(failure);
        PrintWriter writer = response.getWriter();
        writer.write(string);
        writer.flush();
        writer.close();
    }
}
